package com.blogWebAutoTest.common;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.SimpleTimeZone;
import java.util.concurrent.TimeUnit;

public class AutoTestUtils {
    public static ChromeDriver driver;
    public static ChromeDriver createDriver(){
        if  (driver ==null){

//            //无头模式
            ChromeOptions options = new ChromeOptions();
            options.addArguments("-headless");
            driver = new ChromeDriver(options);

//            driver = new ChromeDriver();
            //创建隐式等待
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        }
        return driver;
    }

    //时间格式化
    public List<String> getFormatTimeFileName(){
        List<String> list = new ArrayList<>();
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMdd-HHmmssSS");
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyyMMdd");
        String filename = simpleDateFormat1.format(System.currentTimeMillis());
        String dirname = simpleDateFormat2.format(System.currentTimeMillis());
        list.add(filename);
        list.add(dirname);
        return list;
    }

    //使用格式化的时间做文件名和文件夹名，来保存截图文件
    public void saveScreenShot(String str) throws IOException{
        List<String> list = getFormatTimeFileName();
        //构建了一个包含文件路径的字符串 `filename`，该路径将截图保存到项目目录下的指定文件夹中
        String filename = "./src/test/java/com/blogWebAutoTest/"+list.get(1)+"/"+str+list.get(0)+".png";
        File scrfile =driver.getScreenshotAs(OutputType.FILE);

        //将 'scrfile' 对象中的截图文件复制到 'filename' 字符串指定的路径中，从而保存截图
        FileUtils.copyFile(scrfile,new File(filename));
    }

}
